import apiConfig from '@/api/config';
import ContentList from '@/components/ContentList';
import DeleteWrapper from '@/components/DeleteWrapper';
import PageTitle from '@/components/PageTitle';
import QuickCreator from '@/components/QuickCreator';
import TButton from '@/components/TButton';
import ToolBar from '@/components/Toolbar';
import { useDatabase } from '@/hooks/useDatabase';
import { Form, Input, message, Modal } from 'antd';
import moment from 'moment';
import { useEffect, useMemo, useRef, useState } from 'react';
import Vditor from 'vditor';
import 'vditor/dist/index.css';

import './index.less';

export type MemoT = {
  id: string;
  title: string;
  content: string;
  createTime: moment.Moment | '';
  updateTime: moment.Moment | '';
};

const RESTORE_MEMO_LOCAL_KEY = 'todo-memo-restore';

const DB_CONFIG = {
  init: true,
  getUrl: apiConfig.getMemo.url,
  restoreKey: RESTORE_MEMO_LOCAL_KEY,
  dataMapper: (i: MemoT) => {
    i.createTime = i.createTime ? moment(i.createTime) : '';
    i.updateTime = i.updateTime ? moment(i.updateTime) : '';
    return i;
  },
  createUrl: apiConfig.createMemo.url,
  removeUrl: apiConfig.removeMemo.url,
  updateUrl: apiConfig.updateMemo.url,
};

const Memo = () => {
  const {
    data: memoList = [],
    activeTarget,
    setActiveTarget,
    create,
    remove,
    update,
  } = useDatabase<MemoT>({
    ...DB_CONFIG,
  });

  const [content, setContent] = useState(''); // 真正显示/编辑的内容
  const [show, setShow] = useState(false);

  const vditorRef = useRef<any>(null);
  const [filter, setFilter] = useState('');

  const [vditorReady, setVditorReady] = useState(false); // 编辑器初始化完成滞后于数据就绪，导致感知不到第一次数据灌入，因此用标志位实现数据灌入检测

  const displayList = useMemo<MemoT[]>(() => {
    if (filter) {
      return memoList.filter((i) => i.title.includes(filter));
    } else {
      return memoList;
    }
  }, [memoList, filter]);

  useEffect(() => {
    initEditor();
  }, []);

  useEffect(() => {
    if (!vditorReady) {
      return;
    }
    if (activeTarget && vditorRef.current) {
      vditorRef.current.setValue(activeTarget.content);
    }
  }, [activeTarget, vditorReady]);

  useEffect(() => {
    if (activeTarget) {
      setContent(activeTarget.content);
    } else {
      setContent('');
    }
  }, [activeTarget]);

  const initEditor = () => {
    const container = document.querySelector('#vditor');
    if (!container) {
      return;
    }
    container.innerHTML = '';
    const vditor = new Vditor('vditor', {
      height: '100%',
      mode: 'ir',
      preview: {
        markdown: {
          codeBlockPreview: false,
        },
      },
      blur: (v) => {
        setContent(v);
      },
      after: () => {
        vditorRef.current = vditor;
        setVditorReady(true);
      },
      // toolbar: [],
      cache: {
        enable: false, // 禁用localstorage缓存
      },
    });
  };

  const handleCreate = (v: any) => {
    const newItem = Object.assign({}, v, {
      id: Date.now().toString(),
      createTime: moment().toISOString(),
      updateTime: moment().toISOString(),
      content: '',
    }) as MemoT;
    create(newItem)
      .then(() => {
        message.success(`创建了便笺：${newItem.title}`);
      })
      .catch((e) => {
        message.error('创建失败');
      });
  };

  const handleRemove = (item: MemoT) => {
    remove(item)
      .then(() => {
        message.success('移除成功！');
      })
      .catch((e) => {
        console.error('移除失败', e);
      });
  };

  const handleUpdate = (v?: any) => {
    if (!activeTarget) {
      return;
    }
    const item = Object.assign({}, activeTarget, {
      content,
      title: v?.title || activeTarget.title,
      updateTime: moment().toISOString(),
    });
    update(item)
      .then(() => {
        message.success('已更新');
      })
      .catch((e) => {
        message.error('更新失败');
      })
      .finally(() => {
        setShow(false);
      });
  };

  const renderRight = () => {
    return <></>;
  };

  const renderForm = () => {
    const config = [
      {
        field: 'title',
        label: '便签名',
        required: true,
      },
      {
        field: 'id',
        label: 'id',
        hidden: true,
      },
    ];

    return (
      <Form
        name="basic"
        initialValues={activeTarget || {}}
        onFinish={handleUpdate}
        autoComplete="off"
        style={{ marginTop: '20px' }}
        layout="vertical"
      >
        {config.map((i) => (
          <Form.Item
            label={i.label}
            name={i.field}
            rules={[{ required: i.required || false }]}
            key={i.field}
            hidden={i.hidden || false}
          >
            <Input autoComplete="off" size="small" />
          </Form.Item>
        ))}
        <Form.Item>
          <TButton submit fullWidth>
            确定
          </TButton>
        </Form.Item>
      </Form>
    );
  };

  const renderListItem = (item: MemoT) => {
    return (
      <div className="memo-content-list-item">
        <DeleteWrapper
          onRemove={() => {
            handleRemove(item);
          }}
        >
          <div className="memo-content-list-item__delete">
            <span></span>
          </div>
        </DeleteWrapper>
        <span className={`memo-content-list-item__title`}>{item.title}</span>
        <span className="memo-content-list-item__desc">
          {item.updateTime
            ? `上次更新时间：${item.updateTime.format('YYYY-MM-DD HH:mm')}`
            : ''}
        </span>
      </div>
    );
  };

  const renderContent = () => {
    return (
      <>
        {activeTarget && (
          <PageTitle
            title={activeTarget.title || ''}
            rightTitle={
              <div className="container">
                <TButton
                  onClick={() => {
                    setShow(true);
                  }}
                  plain
                  style={{fontSize: '12px', borderRadius: '10px'}}
                >
                  编辑
                </TButton>
                <TButton
                  onClick={handleUpdate}
                  style={{ height: '24px', marginLeft: '10px' }}
                >
                  保存
                </TButton>
              </div>
            }
            subTitle={
              <div>
                <span>创建时间</span>
                <span
                  style={{
                    color: 'var(--mainColor)',
                    marginLeft: '10px',
                    marginRight: '20px',
                  }}
                >
                  {activeTarget.createTime &&
                    activeTarget.createTime.format('Y-M-D HH:mm')}
                </span>
                <span>更新时间</span>
                <span
                  style={{
                    color: 'var(--mainColor)',
                    marginLeft: '10px',
                    marginRight: '20px',
                  }}
                >
                  {activeTarget.updateTime &&
                    activeTarget.updateTime.format('Y-M-D HH:mm')}
                </span>
              </div>
            }
          />
        )}
        <div className="memo__container">
          <div id="vditor"></div>
          {/* <textarea
            className="memo__textarea"
            value={content}
            onChange={(e) => {
              setContent(e.target.value);
            }}
          /> */}
        </div>
      </>
    );
  };

  const renderLeftActions = () => {
    return (
      <QuickCreator
        defaultFields={{}}
        mainField="title"
        onCreate={handleCreate}
        placeholder="回车快速创建便笺项目"
      />
    );
  };

  return (
    <>
      <ToolBar leftActions={renderLeftActions()} rightActions={renderRight()} />
      <ContentList
        list={displayList}
        activeKey={activeTarget?.id || ''}
        keyField="id"
        onSelect={(key) => {
          const item = (memoList.find((i) => i.id === key) as MemoT) || null;
          setActiveTarget(item);
        }}
        content={renderContent()}
        tools={['search']}
        searchKey="title"
        onSearch={(v) => setFilter(v)}
        sorter={(a: MemoT, b: MemoT) => {
          // 按照更新时间，越新越前
          if (a.updateTime === '' || b.updateTime === '') {
            return 0;
          }
          return b.updateTime.diff(a.updateTime);
        }}
        listRender={renderListItem}
      />

      <Modal
        visible={show}
        onCancel={() => setShow(false)}
        footer={false}
        destroyOnClose
      >
        {renderForm()}
      </Modal>
    </>
  );
};

export default Memo;
